#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/27
# @Author    :Erinyu
# @Email     :yuailing@bbdservice.com
# @File      :IC_UpaidRevolvingLoanLoanCnt
# @Software  :PyCharm

'''eof
name:个人当前未结清循环贷款笔数
code:IC_UpaidRevolvingLoanCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def NaNCheck(str):
    return False if str in null_type_list else True

# 1.判断账户类型和账户状态：个人当前未结清循环贷款笔数
# factor1= (账户类型(PD01AD01) =="R1" and账户状态(PD01BD01) not in ["3"] 的业务机构管理代码（PD01AI02）
# PDA[1.1] - pd01[0.*] - pd01a[1.1]/pd01b[1.1] - pd01ad01[1.1]/PD01AI02[1.1]/PD01BD01[1.1]
# 账户类型 PD01AD01 [1.1]
# 账户状态 PD01BD01 [1.1]
# 业务管理机构代码 PD01AI02 [1.1]
# factor= count （factor1）



def IC_UpaidRevolvingLoanLoanCnt():
    data = IC_DSJ.get('data')
    factor = []
    zero = 0
    # 借贷账户信息 PDA [1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01 [0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                # 基本信息段 PD01A [1.1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                # 最新表现信息段 PD01B [1.1]
                PD01B = getTable(i, 'PD01B', 1, 1)
                if PD01A == [{}] or PD01B == [{}]:
                    return u'缺失值'
                # 因为PD01A和PD01B的occurTimes、iteratorTimes都是1
                # 根据getTable函数定义，它俩都不可能值为0,所以这里就不判断为0的情况了
                else:
                    # 账户类型 PD01AD01 [1.1] == "R1"
                    PD01AD01 = PD01A[0].get('PD01AD01')
                    # 账户状态 PD01BD01 [1.1] not in [ "3"]
                    PD01BD01 = PD01B[0].get('PD01BD01')
                    if not (NaNCheck(PD01AD01) and NaNCheck(PD01BD01)):
                        # 缺失值
                        factor.append(None)
                    else:
                        if PD01AD01 == 'R1' and PD01BD01 not in ['3']:
                            # 业务管理机构代码 PD01AI02 [1.1]
                            PD01AI02 = PD01A[0].get('PD01AI02')
                            if NaNCheck(PD01AI02):
                                # 个人当前未销户且激活状态下的贷记卡机构数+1
                                factor.append(PD01AI02)
                            else:
                                # 缺失值
                                factor.append(None)
                        else:
                            # 不是缺失值，只是不符合条件
                            # 个人当前未销户且激活状态下的贷记卡机构数+0
                            factor.append(0)
                            zero -= 1
    factor = [x for x in factor if x is not None]
    return u'缺失值' if len(factor) == 0 else len(factor) + zero

if __name__ == '__main__':
    file_obj = open(r'IC_DSJ.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False)
    IC_DSJ = IC_DSJ.get('IC_DSJ')
    res = IC_UpaidRevolvingLoanLoanCnt()
    print(res)

result = IC_UpaidRevolvingLoanLoanCnt()